package gift4friend.server.core.GiftManager;

import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import gift4friend.server.core.JDOCreator;
import gift4friend.shared.core.Likeable;
import gift4friend.shared.core.Product;
import gift4friend.shared.core.User;

public class GiftListManager {

	private static PersistenceManager pm;

	public static void addProduct(Long userID, Product p) {

		pm = JDOCreator.getPmfInstance().getPersistenceManager();
		User usr = pm.getObjectById(User.class, userID);
		usr.addProduct(p);
		pm.makePersistent(usr);
		pm.evictAll();
		pm.close();
	}

	public static void addLikeabel(Long userID, Likeable l) {

		pm = JDOCreator.getPmfInstance().getPersistenceManager();
		User usr = pm.getObjectById(User.class, userID);
		usr.addLikeable(l);
		pm.makePersistent(usr);
		pm.evictAll();
		pm.close();
	}

	public static void removeProduct(Long userID, Long productID) {

		pm = JDOCreator.getPmfInstance().getPersistenceManager();
		User usr = pm.getObjectById(User.class, userID);

		Iterator<Product> it = usr.productIterator();

		Product p;
		while (it.hasNext()) {
			p = it.next();

			if (p.getId() == productID) {
				usr.removeProduct(p);
			}
		}

		pm.makePersistent(usr);
		pm.evictAll();
		pm.close();
	}

	public static void removeLikeable(Long userID, Long likeableID) {

		pm = JDOCreator.getPmfInstance().getPersistenceManager();
		User usr = pm.getObjectById(User.class, userID);

		Iterator<Likeable> it = usr.likeableIterator();

		Likeable l;
		while (it.hasNext()) {
			l = it.next();

			if (l.getId() == likeableID) {
				usr.removeLikeable(l);
			}
		}

		pm.makePersistent(usr);
		pm.evictAll();
		pm.close();
	}

	public static User getUser(Long userID) {
		pm = JDOCreator.getPmfInstance().getPersistenceManager();
		User usr = pm.getObjectById(User.class, userID);
		pm.close();

		return usr;
	}

	public static User getUser(String mailAddress) {
		Query query = pm.newQuery(User.class);

		List<User> list;
		list = (List<User>) query.execute();

		for (User u : list) {
			if (u.getEmail().equals(mailAddress))
				return u;
		}

		return null;
	}

}
